package com.yw.wanandroid.ui.v


import android.util.Log
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.yw.wanandroid.R
import com.yw.wanandroid.base.BaseFragment
import com.yw.wanandroid.databinding.FragmentHomeBinding
import com.yw.wanandroid.ui.adapter.HomeAdapter
import com.yw.wanandroid.ui.adapter.HomeTopAdapter
import com.yw.wanandroid.ui.vm.HomeViewModel

class HomeFragment : BaseFragment<FragmentHomeBinding>() {
    val model: HomeViewModel by activityViewModels()

    override fun getLayoutId(): Int {
        return R.layout.fragment_home
    }

    override fun subscribeUi(binding: FragmentHomeBinding) {
        bind.apply {
            ftHomeList.layoutManager = LinearLayoutManager(activity)
            val adapter = HomeAdapter(arrayListOf())
            ftHomeList.adapter = adapter
            ftHomeToplist.layoutManager = LinearLayoutManager(activity)
            val topAdapter = HomeTopAdapter(arrayListOf())
            ftHomeToplist.adapter = topAdapter

            model.toplist.observe(this@HomeFragment,
                {
                    if (it.isNotEmpty()) {
                        topAdapter.list = it
                        topAdapter.notifyDataSetChanged()
                    }
                })
            model.articleList.observe(this@HomeFragment, {
                if (model.page == 0) {
                    adapter.list.clear()
                    adapter.list.addAll(it)
                } else {
                    adapter.list.addAll(it)
                }
                adapter.notifyDataSetChanged()
                ftHomeRefresh.finishRefresh(true)
                ftHomeRefresh.finishLoadMore(true)
            })
            ftHomeRefresh.setOnRefreshListener {
                model.getHomeArticle(true)
                Log.d("=====", "subscribeUi: 加载成功")

            }
            ftHomeRefresh.setOnLoadMoreListener {
                model.getHomeArticle(false)
            }
            model.getHomeTopArticle()
            model.getHomeArticle(true)
        }
    }
}


